<template>
  <PageWrapper v-auth="'crm:c_project_application:info'" :title="orderInfoData?.projectName" contentBackground>
    <template #extra>
      <a-button type="primary" @click="quoteAdd">报价</a-button>
      <a-button type="dashed" @click="warranty">质保</a-button>
      <a-button type="primary" @click="uploadContract">上传合同</a-button>
      <a-button type="dashed" @click="acceptance">验收合格</a-button>
    </template>

    <a-card title="项目信息" :bordered="false">
      <a-descriptions size="small" :column="3">
        <a-descriptions-item label="项目编号">{{ orderInfoData?.projectNumber }}</a-descriptions-item>
        <a-descriptions-item label="项目描述">{{ orderInfoData?.projectDescription }}</a-descriptions-item>
        <a-descriptions-item label="工程详细地址">{{ orderInfoData?.library?.address }}</a-descriptions-item>
        <a-descriptions-item label="项目状态">{{ orderInfoData?.projectStatus }}</a-descriptions-item>

        <a-descriptions-item label="发包单位">
          <a href="#" @click="handleContractingUnitView(orderInfoData?.contractingUnitVo.id)">{{
            orderInfoData?.contractingUnitVo?.name
          }}</a></a-descriptions-item
        >
        <a-descriptions-item label="所属库">
          <a href="#" @click="handleLibraryView(orderInfoData?.library.id)">{{ orderInfoData?.library?.name }}</a></a-descriptions-item
        >
        <a-descriptions-item label="总包主体">
          <a href="#" @click="handleCompanyInfoView(orderInfoData?.companyInfo.id)">{{ orderInfoData?.companyInfo?.companyName }}</a>
        </a-descriptions-item>

        <a-descriptions-item label="项目图纸">
          <a
            href="#"
            v-if="orderInfoData?.projectDrawings != null && orderInfoData?.projectDrawings != ''"
            @click="handleViewFile(orderInfoData?.projectDrawings)"
          >
            查看</a
          >
        </a-descriptions-item>
        <a-descriptions-item label="附件">
          <a
            href="#"
            v-if="orderInfoData?.attachmentUrl != null && orderInfoData?.attachmentUrl != ''"
            @click="handleViewFile(orderInfoData?.attachmentUrl)"
          >
            查看</a
          >
        </a-descriptions-item>

        <a-descriptions-item label="质保金合计(含税)">
          <a>{{ orderInfoData?.totalGuaranteeDeposit }}</a>
        </a-descriptions-item>
<!--        <a-descriptions-item label="项目合同">
          <a v-for="(item, index) in orderInfoData?.contract" :key="index">
            <span @click="handleViewFile(item.contractFile)">{{ item.contractNo }}|</span>
          </a>
        </a-descriptions-item>-->
      </a-descriptions>
    </a-card>
    <a-card title="项目经营数据" :bordered="false">
      <a-row>
        <a-col :span="6"><a-statistic title="施工合同金额(元)" :precision="2" :value="orderInfoData?.contractPrice" /></a-col>
        <a-col :span="6"><a-statistic title="子项目合同金额合计（含税）" :precision="2" :value="orderInfoData?.subProjectAmount" /></a-col>
        <a-col :span="6"><a-statistic title="管理费扣款" :precision="2" :value="orderInfoData?.manageFee" /></a-col>
        <a-col :span="6"> <a-statistic title="费用报销金额(元)" :precision="2" :value="orderInfoData?.reimbursement" /></a-col>
        <a-col :span="6"><a-statistic title="项目收款(收款登记)(元)" :precision="2" :value="orderInfoData?.totalReceipts" /></a-col>
        <a-col :span="6"><a-statistic title="付款金额(元)" :precision="2" :value="orderInfoData?.paymentTotal" /></a-col>
        <a-col :span="6">
          <a-tooltip title="收款金额-付款金额-报销-管理费-应交票税" placement="left">
            <div style="display: inline-flex; align-items: center; gap: 4px">
              <a-statistic title="可用余额" :precision="2" :value="orderInfoData?.availableBalance" />
              <QuestionCircleOutlined style="color: #999; cursor: help" />
            </div>
          </a-tooltip>
        </a-col>
        <a-col :span="6"></a-col>
        <a-col :span="6">
          <a-tooltip title="施工合同金额-项目收款" placement="left">
            <div style="display: inline-flex; align-items: center; gap: 4px">
              <a-statistic title="项目未收款金额(元)" :precision="2" :value="orderInfoData?.projectUncollectedPayment" />
              <QuestionCircleOutlined style="color: #999; cursor: help" />
            </div>
          </a-tooltip>
        </a-col>
        <a-col :span="6">
          <a-tooltip title="子项目合同金额合计-付款金额" placement="left">
            <div style="display: inline-flex; align-items: center; gap: 4px">
              <a-statistic title="子项未付款金额(元)" :precision="2" :value="orderInfoData?.subProjectNonPayment" />
              <QuestionCircleOutlined style="color: #999; cursor: help" />
            </div>
          </a-tooltip>
        </a-col>
      </a-row>
    </a-card>

    <a-card title="票据信息" :bordered="false">
      <a-row>
        <a-col :span="8"><a-statistic title="开票金额(元)" :precision="2" :value="orderInfoData?.invoicingTotal" /></a-col>
        <a-col :span="8"><a-statistic title="收票金额(元)" :precision="2" :value="orderInfoData?.receiptsTotal" /></a-col>
        <a-col :span="8"></a-col>
        <a-col :span="8"><a-statistic title="开票税费(元)" :precision="2" :value="orderInfoData?.totalTaxAmount" /></a-col>
        <a-col :span="8"><a-statistic title="收票税额(元)" :precision="2" :value="orderInfoData?.receiptsTaxTotal" /></a-col>
        <a-col :span="8"></a-col>
        <a-col :span="8"><a-statistic title="开票合计含税(元)" :precision="2" :value="orderInfoData?.totalInvoiceTax" /></a-col>
        <a-col :span="8"><a-statistic title="收票合计含税(元)" :precision="2" :value="orderInfoData?.receiptsAndTaxTotal" /></a-col>
        <a-col :span="8">
          <a-tooltip title="开票税额-收票税额" placement="left">
            <div style="display: inline-flex; align-items: center; gap: 4px">
              <a-statistic title="应交票税(元)" :precision="2" :value="orderInfoData?.invoiceTaxPayable" />
              <QuestionCircleOutlined style="color: #999; cursor: help" />
            </div>
          </a-tooltip>
        </a-col>
        <a-col :span="8">
          <a-tooltip title="施工合同金额-开票合计" placement="left">
            <div style="display: inline-flex; align-items: center; gap: 4px">
              <a-statistic title="未开票金额(元)" :precision="2" :value="orderInfoData?.uninvoicedAmount" />
              <QuestionCircleOutlined style="color: #999; cursor: help" />
            </div>
          </a-tooltip>
        </a-col>
        <a-col :span="8">
          <a-tooltip title="子项目合同金额（含税）- 收票合计含税（含税）" placement="left">
            <div style="display: inline-flex; align-items: center; gap: 4px">
              <a-statistic title="未收票金额(元)" :precision="2" :value="orderInfoData?.uncollectedAmount" />
              <QuestionCircleOutlined style="color: #999; cursor: help" />
            </div>
          </a-tooltip>
        </a-col>

        <!--        <a-col :span="4"><a-statistic title="总项目报价(元)" :value="orderInfoData?.totalProjectQuotation" /></a-col>
        <a-col :span="4"><a-statistic title="未收款(元)" :value="orderInfoData?.uncollectedPayment" /></a-col>


        <a-col :span="4"><a-statistic title="票税合计(元)" :value="orderInfoData?.totalInvoiceTax" /></a-col>
        <a-col :span="4"><a-statistic title="子项目合同金额合计(含税)(元)" :value="orderInfoData?.subProjectAmount" /></a-col>-->
      </a-row>
    </a-card>

    <a-card title="项目进度" :bordered="false">
      <a-row>
        <a-col :span="4">
          <a-tooltip :title="orderInfoData?.invoicingProgress + '%'">
            <QuestionCircleOutlined style="color: #999; cursor: help" />
            <a-progress
              :stroke-color="{ '0%': '#ea2a2a', '100%': '#45df11' }"
              type="circle"
              :percent="orderInfoData?.invoicingProgress"
              :format="(percent) => `开票`"
            />
          </a-tooltip>
        </a-col>
        <a-col :span="4">
          <a-tooltip :title="orderInfoData?.receivingProgress + '%'">
            <QuestionCircleOutlined style="color: #999; cursor: help" />
            <a-progress
              :stroke-color="{ '0%': '#ea2a2a', '100%': '#45df11' }"
              type="circle"
              :percent="orderInfoData?.receivingProgress"
              :format="(percent) => `收款`"
            />
          </a-tooltip>
        </a-col>
        <a-col :span="4">
          <a-tooltip :title="orderInfoData?.paymentProgress + '%'">
            <QuestionCircleOutlined style="color: #999; cursor: help" />
            <a-progress
              :stroke-color="{ '0%': '#ea2a2a', '100%': '#45df11' }"
              type="circle"
              :percent="orderInfoData?.paymentProgress"
              :format="(percent) => `付款`"
            />
          </a-tooltip>
        </a-col>
        <a-col :span="4">
          <a-tooltip :title="orderInfoData?.subProjectProgress + '%'">
            <QuestionCircleOutlined style="color: #999; cursor: help" />
            <a-progress
              :stroke-color="{ '0%': '#ea2a2a', '100%': '#45df11' }"
              type="circle"
              :percent="orderInfoData?.subProjectProgress"
              :format="(percent) => `子项目`"
            />
          </a-tooltip>
        </a-col>
      </a-row>
    </a-card>

    <a-card title="流程进度" :bordered="false">
      <a-steps :current="currentStep" progress-dot size="small">
        <a-step v-for="(item, index) in allSteps" :key="index" @click="updateStatue(orderInfoData?.id, item.newStatus)" :title="item.newStatus">
          <template #description>
            <p>{{ item.changeTime }}</p>
            <div>{{ item.remark }}</div>
          </template>
        </a-step>
      </a-steps>
    </a-card>

    <!--子项目-->
    <SubProjectModal :projectId="orderInfoData?.id"> </SubProjectModal>

    <!--任务-->
    <CTaskModal :projectId="orderInfoData?.id"> </CTaskModal>

    <a-tabs v-model:activeKey="activeTabKey" style="margin-left: 15px">
      <a-tab-pane key="payment" :force-render="true" tab="付款记录">
        <PaymentRequestModal ref="paymentRef" :projectId="orderInfoData?.id"> </PaymentRequestModal>
      </a-tab-pane>
      <a-tab-pane key="invoice" :force-render="true" tab="收票记录">
        <PaymentInvoiceModal  ref="invoiceRef" :projectId="orderInfoData?.id"> </PaymentInvoiceModal>
      </a-tab-pane>
      <a-tab-pane key="apply" :force-render="true" tab="开票记录">
        <InvoiceApplyListInfoModal ref="applyRef" :projectId="orderInfoData?.id"> </InvoiceApplyListInfoModal>
      </a-tab-pane>
      <a-tab-pane key="record" :force-render="true" tab="收款记录">
        <PaymentRecordListInfoModal ref="recordRef" :projectId="orderInfoData?.id"> </PaymentRecordListInfoModal>
      </a-tab-pane>
      <a-tab-pane key="acceptance" :force-render="true" tab="验收记录">
        <AcceptanceRecordModal ref="acceptanceRef" :projectId="orderInfoData?.id"> </AcceptanceRecordModal>
      </a-tab-pane>

      <a-tab-pane key="contract" :force-render="true" tab="合同记录">
        <ContractInfoModal  ref="contractRef" :projectId="orderInfoData?.id"> </ContractInfoModal>
      </a-tab-pane>

      <a-tab-pane key="fileRecord" :force-render="true" tab="相关文件">
        <fileRecordModal  ref="fileRef" :projectId="orderInfoData?.id"> </fileRecordModal>
      </a-tab-pane>

      <a-tab-pane key="projectHeadQuotesInfo" :force-render="true" tab="总项目报价记录">
        <ProjectHeadQuotesInfoModal ref="quoteRef" :projectId="orderInfoData?.id"> </ProjectHeadQuotesInfoModal>
      </a-tab-pane>
    </a-tabs>
  </PageWrapper>
  <!--总项目报价-->
  <projectheadquoteModal ref="registerModal" @success="handleSuccess"></projectheadquoteModal>
  <!--质保-->
  <WarrantyAddModal ref="warrantyModal" @success="handleSuccess"></WarrantyAddModal>
  <!--上传合同-->
  <CContractModal ref="registerContractModal" @success="handleSuccess"></CContractModal>
  <!--验收合格-->
  <CAcceptanceRecordModal ref="registerAcceptanceModal" @success="handleSuccess"></CAcceptanceRecordModal>
  <!-- 引入 ViewFileDetail 组件 -->
  <ViewFileDetail ref="viewFileDetailRef" @view-file="viewFileDetail = $event"></ViewFileDetail>

  <!-- 修改状态 -->
  <CProjectStatusLogModal ref="projectStatusLogRegisterModal" @success="handleSuccess"></CProjectStatusLogModal>

  <CLibraryModal ref="registerLibraryModal" @success="handleSuccess"></CLibraryModal>
  <CContractingUnitModal ref="registerContractingUnitModal" @success="handleSuccess"></CContractingUnitModal>
  <CCompanyInfoModal ref="registerCompanyInfoModal" @success="handleSuccess"></CCompanyInfoModal>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref, reactive,nextTick } from 'vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Divider, Card, Empty, Descriptions, Steps, Tabs, Statistic, Progress } from 'ant-design-vue';
  import { getOrderInfo } from './orderInfo.api';
  import { refundTimeTableSchema } from './data';
  import { QuestionCircleOutlined } from '@ant-design/icons-vue';
  import CTaskModal from '../task/CTaskListInfo.vue';
  import WarrantyAddModal from '../warranty/components/CWarrantyModal.vue';
  import PaymentRequestModal from '../paymentrequest/CPaymentRequestListInfo.vue';
  import InvoiceApplyListInfoModal from '../invoiceapply/CInvoiceApplyListInfo.vue';
  import PaymentRecordListInfoModal from '../paymentrecord/CPaymentRecordListInfo.vue';
  import PaymentInvoiceModal from '../paymentInvoice/CPaymentInvoiceListInfo.vue';
  import ContractInfoModal from '../contrac/CContractListInfo.vue';
  import AcceptanceRecordModal from '../acceptancerecord/CAcceptanceRecordListInfo.vue';
  import fileRecordModal from '../filerecord/CFileRecordListInfo.vue';
  import ProjectHeadQuotesInfoModal from '../projectheadquote/CProjectHeadQuotesListInfo.vue';
  import projectheadquoteModal from '../projectheadquote/components/CProjectHeadQuotesModal.vue';
  import SubProjectModal from '../subproject/CSubProjectListInfo.vue';
  import { useRoute } from 'vue-router';
  import { useTabs } from '@/hooks/web/useTabs';
  import { ajaxGetDictItems } from '../common.api';
  import CContractModal from '@/views/contrac/components/CContractModal.vue';
  import CAcceptanceRecordModal from '@/views/acceptancerecord/components/CAcceptanceRecordModal.vue';
  import ViewFileDetail from '@/components/FileView/ViewFileDetail.vue';
  import CProjectStatusLogModal from '@/views/projectstatuslog/components/CProjectStatusLogModal.vue';
  import CLibraryModal from '@/views/library/components/CLibraryModal.vue';
  import CContractingUnitModal from '@/views/contractingunit/components/CContractingUnitModal.vue';
  import CCompanyInfoModal from '@/views/companyInfo/components/CCompanyInfoModal.vue';
  const { createMessage } = useMessage();
  const registerModal = ref();
  const registerCompanyInfoModal = ref();
  const registerContractingUnitModal = ref();
  const registerLibraryModal = ref();
  const registerAcceptanceModal = ref();
  const registerContractModal = ref();
  const warrantyModal = ref();
  const projectStatusLogRegisterModal = ref();

 // 在 setup() 里拿到子组件实例
  const paymentRef   = ref()
  const invoiceRef   = ref()
  const applyRef     = ref()
  const recordRef    = ref()
  const acceptanceRef= ref()
  const contractRef  = ref()
  const fileRef      = ref()
  const quoteRef     = ref()

  // 从子组件获取 viewFileDetail 方法
  const viewFileDetail = ref();
  const viewFileDetailRef = ref();
  // 在 table 的插槽中使用 viewFileDetail 方法
  function handleViewFile(url) {
    viewFileDetail.value(url);
  }

  const activeTabKey = ref('payment');
  export default defineComponent({
    components: {
      CCompanyInfoModal,
      CContractingUnitModal,
registerCompanyInfoModal,
      QuestionCircleOutlined,
      CTaskModal,
      CLibraryModal,
      registerLibraryModal,
      CProjectStatusLogModal,
      ViewFileDetail,
      CAcceptanceRecordModal,
      CContractModal,
      SubProjectModal,
      WarrantyAddModal,
      BasicTable,
      PaymentRequestModal,
      InvoiceApplyListInfoModal,
      PaymentRecordListInfoModal,
      PaymentInvoiceModal,
      ContractInfoModal,
      AcceptanceRecordModal,
      fileRecordModal,
      projectheadquoteModal,
      PageWrapper,
      ProjectHeadQuotesInfoModal,
      [Divider.name]: Divider,
      [Statistic.name]: Statistic,
      [Progress.name]: Progress,

      [Card.name]: Card,
      Empty,
      [Descriptions.name]: Descriptions,
      [Descriptions.Item.name]: Descriptions.Item,
      [Steps.name]: Steps,
      [Steps.Step.name]: Steps.Step,
      [Tabs.name]: Tabs,
      [Tabs.TabPane.name]: Tabs.TabPane,
    },
    setup() {
      const projectId = ref<string | null>(null);
      const contractIds = ref<string | null>(null);

      const projectStatusLogs = ref<any[]>([]);
      const currentStep = ref<number>(0);
      // 承包商下拉框选项
      let contractorOptions = ref();
      // 使用 useRoute 获取当前路由信息
      const route = useRoute();
      const orderInfoData = ref();
      const refundTimeTableData = ref([]);

      const [registerTimeTable] = useTable({
        // title: '子项目',
        columns: refundTimeTableSchema,
        pagination: true,
        dataSource: refundTimeTableData,
        showIndexColumn: false,
        scroll: { y: 300 },
      });

      // 定义所有可能的步骤
      const allSteps = reactive([
        { newStatus: '前期', remark: '', changeTime: '', num: 0 },
        { newStatus: '立项', remark: '', changeTime: '', num: 1 },
        { newStatus: '进行中', remark: '', changeTime: '', num: 2 },
        { newStatus: '验收阶段', remark: '', changeTime: '', num: 3 },
        { newStatus: '质保阶段', remark: '', changeTime: '', num: 4 },
        { newStatus: '完成', remark: '', changeTime: '', num: 5 },
        { newStatus: '废除', remark: '', changeTime: '', num: 6 },
      ]);
      // 自定义筛选逻辑
      const filterOption = (input: string, option: any) => {
        return option.label.toLowerCase().includes(input.toLowerCase());
      };

      /**
       * 上传合同
       */
      function uploadContract() {
        const record = { projectId: projectId.value, isProject: false };
        registerContractModal.value.disableSubmit = false;
        registerContractModal.value.add(record);
      }

      async function orderInfo() {
        try {
          const params = { id: projectId.value };
          const result = await getOrderInfo(params);

          orderInfoData.value = result;
          contractIds.value = result.contractId;

          // 动态设置流程进度数据
          projectStatusLogs.value = result.projectStatusLogList || [];
          //
          const data = projectStatusLogs.value[0];
          let statusFlag = true;
          // 根据返回的流程进度日志更新描述和时间
          let num = 0;
          allSteps.forEach((step, index) => {
            const log = projectStatusLogs.value.find((log) => log.newStatus === step.newStatus);
            if (log && statusFlag) {
              step.remark = log.remark || '';
              step.changeTime = log.changeTime || '';
              currentStep.value = step.num;
              if (data.newStatus === log.newStatus) {
                //后面的状态就不处理了
                statusFlag = false;
              }
            } else {
              step.remark = '';
              step.changeTime = '';
            }
          });

          //子项目
          const cSubProjectList = result.csubProjectList || [];

          for (var i = 0; i < cSubProjectList.length; i++) {
            const subProject = cSubProjectList[i];
            const refundTimeTable = {
              t1: subProject.subProjectName, //项目名称
              t2: subProject.contactId, //分包商
              t3: subProject.userId,
              t4: subProject.status,
            };
            refundTimeTableData.value.push(refundTimeTable);
          }
        } catch (error) {}
      }


      const { setTitleByPath } = useTabs();
      onMounted(async () => {
        projectId.value = route.query.projectId as string;
        await orderInfo();
        //设置tab名称
        const title = orderInfoData.value?.projectName? `主项目 - ${orderInfoData.value.projectName}`
          : '主项目详情';
        setTitleByPath(title,route.fullPath);
      });

      async function dictCode(dictCode, dataId) {
        if (dataId) {
          const params = { dataId: dataId };
          const result = await ajaxGetDictItems(dictCode, params);
          if (result) {
            return result.text;
          }
          return dataId;
        }
      }

      /**
       * 刷新
       */
      function handleSuccess() {
        orderInfo();
        handleTabClick();
      }

      function quoteAdd() {
        const defaultValueRef = reactive<Record<string, any>>({
          projectId: projectId.value,
        });
        registerModal.value.disableSubmit = false;
        registerModal.value.add(defaultValueRef);
      }

      /**
       * 质保
       */
      function warranty() {
        const defaultValueRef = reactive<Record<string, any>>({
          projectId: projectId.value,
          contractId: contractIds.value,
        });
        warrantyModal.value.disableSubmit = false;
        warrantyModal.value.add(defaultValueRef);
      }

      /**
       * 验收
       */
      function acceptance() {
        const defaultValueRef = reactive<Record<string, any>>({
          projectId: projectId.value,
        });
        registerAcceptanceModal.value.disableSubmit = false;
        registerAcceptanceModal.value.add(defaultValueRef);
      }

      /**
       * 修改状态
       */
      function updateStatue(projectid, newStatus) {
        const defaultValueRef = reactive<Record<string, any>>({
          projectId: projectid,
          newStatus: newStatus,
        });
        projectStatusLogRegisterModal.value.disableSubmit = false;
        projectStatusLogRegisterModal.value.add(defaultValueRef);
        orderInfo();
      }

      /**
       * 库
       * @param id
       */
      function handleLibraryView(id) {
        registerLibraryModal.value.disableSubmit = true;
        registerLibraryModal.value.info(id);
      }

      function handleContractingUnitView(id) {
        registerContractingUnitModal.value.disableSubmit = true;
        registerContractingUnitModal.value.info(id);
      }
      function handleCompanyInfoView(id) {
        registerCompanyInfoModal.value.disableSubmit = true;
        registerCompanyInfoModal.value.info(id);
      }


      function handleTabClick() {
         paymentRef.value?.refresh?.()
        invoiceRef.value?.refresh?.()
        applyRef.value?.refresh?.()
         recordRef.value?.refresh?.()
        acceptanceRef.value?.refresh?.()
        contractRef.value?.refresh?.()
        fileRef.value?.refresh?.()
         quoteRef.value?.refresh?.()

}

      return {
        quoteAdd,
        handleContractingUnitView,
        handleLibraryView,
        registerTimeTable,
        orderInfo,
        refundTimeTableData,
        route,
        orderInfoData,
        handleSuccess,
        projectStatusLogs,
        currentStep,
        allSteps,
        contractorOptions,
        filterOption,
        activeTabKey,
        paymentRef,
        invoiceRef,
        applyRef,
        recordRef,
        acceptanceRef,contractRef,
        fileRef,
        quoteRef,
        dictCode,
        registerModal,
        uploadContract,
        registerContractModal,
        acceptance,
        registerAcceptanceModal,
        handleViewFile,
        viewFileDetail,
        warrantyModal,
        warranty,
        updateStatue,
        handleTabClick,
        projectStatusLogRegisterModal,
        registerLibraryModal,
        registerContractingUnitModal,
        handleCompanyInfoView,
        registerCompanyInfoModal,
      };
    },
  });
</script>
<style lang="less" scoped>
  .custom-label {
    font-weight: bold;
    color: gray;
    font-size: 18px;
  }
</style>
